package com.xpec.c4.service.group.datalayer.infinispan;

import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.infinispan.executors.ExecutorFactory;
import org.infinispan.util.TypedProperties;

public class XTransportExecutorFactory implements ExecutorFactory{
	
	   private final static AtomicInteger counter = new AtomicInteger(0);

	   @Override
	   public ExecutorService getExecutor(Properties p) {
	      TypedProperties tp = TypedProperties.toTypedProperties(p);
	      int maxThreads = tp.getIntProperty("maxThreads", 1);
	      int queueSize = tp.getIntProperty("queueSize", 100000);
	      final int threadPrio = tp.getIntProperty("threadPriority", Thread.MIN_PRIORITY);
	      final String threadNamePrefix = tp.getProperty("threadNamePrefix", tp.getProperty("componentName", "Thread"));
	      ThreadFactory tf = new ThreadFactory() {
	         @Override
	         public Thread newThread(Runnable r) {
	            Thread th = new Thread(r, threadNamePrefix + "-" + counter.getAndIncrement());
	            th.setDaemon(true);
	            th.setPriority(threadPrio);
	            return th;
	         }
	      };

	      return new InfinispanThreadPoolExecutor(maxThreads, maxThreads,
	                                    0L, TimeUnit.MILLISECONDS,
	                                    new LinkedBlockingQueue<Runnable>(queueSize),
	                                    tf);
	   }

}
